import { FC, useRef, useMemo } from "react";
import { Button, Drawer, DrawerProps } from "antd";
import { useEffect } from "react";

import { Form } from "@formily/core";

import { CheckOutlined, RollbackOutlined } from "@ant-design/icons";
import { getValidateMessage } from "@/utils/validate-rules/message";
import { getSubmitFormValues } from "@ey-utils/utils/formily-utils/getSubmitFormValues";
import { WithNormalRender } from "@/biz-components/hoc-form/with-normal";
import { DynamicObjectAny } from "@/typings";

import { message } from "antd";
import {getFormValues} from "@/hooks";

interface FormPageDrawerProps extends DrawerProps {
  onCancel: () => void;
  onConfirm: (values: any) => void;
  defaultValue?: any;
  width?: string;
  pageCode: string;
  pageType?: "NORMAL" | "DETAIL";
  eventMap?: DynamicObjectAny;
  formEffects?: (form: Form) => void;
  validateFormValues?: (formValues: any) => Promise<string>;
}

const FormPageDrawer: FC<FormPageDrawerProps> = (props) => {
  const {
    visible,
    onCancel,
    onConfirm,
    defaultValue,
    pageCode,
    pageType,
    width,
    eventMap,
    formEffects,
    title,
    validateFormValues,
    ...restProps
  } = props;
  const formRef = useRef<Form<any>>();

  const WithNormalComp = useMemo(() => {
    return WithNormalRender({});
  }, []);

  useEffect(() => {
    if (!visible) {
      formRef.current?.reset();
      return;
    }

    Object.keys(defaultValue || {}).forEach((key) => {
      formRef.current?.setValuesIn(key, defaultValue?.[key]);
    });
  }, [visible, defaultValue]);

  const submit = (formValues: any) => {
    onConfirm?.(formValues);

    formRef.current?.reset();

    handleRollbackClick();
  };

  const handleCheckClick = async () => {
    if (formRef.current) {
      getFormValues(formRef.current).then((formValues) => {
        if (validateFormValues) {
          validateFormValues(formValues)
            .then(() => {
              submit(formValues);
            })
            .catch((err) => {
              if (err) {
                message.warning(err);
              }
            });
        } else {
          submit(formValues);
        }
      });
    }
  };

  const handleRollbackClick = () => {
    onCancel?.();
  };

  return (
    <Drawer
      title={title || "请填写"}
      placement="right"
      closable={false}
      onClose={handleRollbackClick}
      visible={visible}
      width={width}
      maskClosable={false}
      destroyOnClose={true}
      footer={
        <div className="page__foot">
          <div className="content__slot__left">
            <Button
              onClick={handleRollbackClick}
              icon={<RollbackOutlined />}
              className="reset-btn"
            >
              {getValidateMessage("common.cancel", true)}
            </Button>
          </div>
          <div className="page__foot_right_btns">
            <Button
              onClick={handleCheckClick}
              type="primary"
              icon={<CheckOutlined />}
            >
              {getValidateMessage("common.confirm", true)}
            </Button>
          </div>
        </div>
      }
      bodyStyle={{
        overflowX: "hidden",
      }}
    >
      <WithNormalComp
        {...restProps}
        type={pageType || "NORMAL"}
        pageCode={pageCode}
        flag={pageCode}
        needFooter={false}
        eventMap={eventMap}
        formConfigs={{
          initialValues: {
            ...defaultValue,
          },
          effects: (form) => {
            formRef.current = form;

            formEffects?.(form);
          },
        }}
      />
    </Drawer>
  );
};

FormPageDrawer.defaultProps = {
  width: "90%",
  pageType: "NORMAL",
};

export default FormPageDrawer;
